package com.dwxt.cdms.applets.service;

import com.dwxt.cdms.api.common.utils.DateUtil;
import com.dwxt.cdms.applets.dto.IndexGraphDayResDTO;
import com.dwxt.cdms.applets.dto.IndexGraphResDTO;
import com.dwxt.cdms.applets.dto.IndexReqDTO;
import com.dwxt.cdms.base.Graph;
import com.dwxt.cdms.constant.DateCategory;
import com.dwxt.cdms.constant.EquipCategory;
import com.dwxt.cdms.constant.ReceiveDataType;
import com.dwxt.cdms.dao.BloodSugarMapper;
import com.dwxt.cdms.dao.BlutdruckMapper;
import com.dwxt.cdms.dao.base.DictValueMapper;
import com.dwxt.cdms.dao.poct.Poct4Mapper;
import com.dwxt.cdms.dao.poct.Poct8Mapper;
import com.dwxt.cdms.dao.yumeng.BpDataMapper;
import com.dwxt.cdms.dao.yumeng.HrDataMapper;
import com.dwxt.cdms.dao.yumeng.SleepDataMapper;
import com.dwxt.cdms.dao.yumeng.StepDataMapper;
import com.dwxt.cdms.entity.BloodSugar;
import com.dwxt.cdms.entity.Blutdruck;
import com.dwxt.cdms.entity.oufu.OuFuData;
import com.dwxt.cdms.entity.yumeng.BpData;
import com.dwxt.cdms.entity.yumeng.HrData;
import com.dwxt.cdms.entity.yumeng.SleepData;
import com.dwxt.cdms.service.HeartVoiceService;
import com.dwxt.cdms.service.LbWatchService;
import com.dwxt.cdms.service.OuFuService;
import com.dwxt.cdms.view.wristwatch.NewSleepDataView;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.DateUtils;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GraphService {

    @Autowired
    private HrDataMapper hrDataMapper;

    @Autowired
    private BpDataMapper bpDataMapper;

    @Autowired
    private BlutdruckMapper blutdruckMapper;

    @Autowired
    private BloodSugarMapper bloodSugarMapper;

    @Autowired
    private SleepDataMapper sleepDataMapper;

    @Autowired
    private DictValueMapper dictValueMapper;

    @Autowired
    private OuFuService ouFuService;

    @Autowired
    private HeartVoiceService heartVoiceService;

    @Autowired
    private StepDataMapper stepDataMapper;

    @Autowired
    private Poct4Mapper poct4Mapper;

    @Autowired
    private Poct8Mapper poct8Mapper;

    @Autowired
    private LbWatchService lbWatchService;


    public BaseResult index(Integer customerId) {
        List list = new ArrayList<>();
        //心率
        Graph hrGraph;
        List<HrData> hrDataList = hrDataMapper.selectHrDataGraph(customerId);
        if (hrDataList.size() <= 0) {
            List<OuFuData> ouFuDataList = ouFuService.selectOuFuGraph(customerId, ReceiveDataType.HEARTBEAT);
            hrGraph = getBeatGraph(ouFuDataList);
        } else {
            Collections.reverse(hrDataList);
            hrGraph = getHrGraph(hrDataList);
        }
        //血氧
        List<BpData> bpDataList = bpDataMapper.selectBpDataGraph(customerId);
        Collections.reverse(bpDataList);
        Graph bpGraph = getBpGraph(bpDataList);
        //血压
        Graph blutGraph;
        List<Blutdruck> blutdruckList = blutdruckMapper.selectBlutdruckGraph(customerId);
        Collections.reverse(blutdruckList);
        blutGraph = getBlutGraph(blutdruckList);
//        if (blutdruckList.size() > 0) {
//            Collections.reverse(blutdruckList);
//            blutGraph = getBlutGraph(blutdruckList);
//        } else if (bpDataList.size() > 0) {
//            Collections.reverse(bpDataList);
//            blutGraph = getBlutGraph(bpDataList);
//        } else {
//            List<OuFuData> ouFuDataList = ouFuService.selectOuFuGraph(customerId, ReceiveDataType.BLOOD_PRESSURE);
//            blutGraph = getBlutGraph(ouFuDataList);
//        }

        //心建
        Graph blutHrGraph = getBlutHrGraph(blutdruckList);
        //血糖
        List<BloodSugar> bloodSugarList = bloodSugarMapper.selectBloodSugarGraph(customerId);
        Collections.reverse(bloodSugarList);
        Graph bloodGraph = getBloodGroup(bloodSugarList);
        //睡眠
        Map sleepGraph = new HashMap();
        //手环
        List<SleepData> sleepDataList = sleepDataMapper.selectSleepGraph(customerId);
        if (sleepDataList.size() <= 0) {
            //手表
            NewSleepDataView newSleepDataView = ouFuService.getNewSleepDataView(customerId);
            if (newSleepDataView != null) {
                sleepGraph = getSleepGraph(newSleepDataView);
            }
        } else {
            sleepGraph = getSleepGraph(sleepDataList);
        }

        list.add(hrGraph);
        list.add(bpGraph);
        list.add(blutGraph);
        list.add(bloodGraph);
        list.add(blutHrGraph);
        list.add(sleepGraph);

        return BaseResult.ok(list);
    }

    private Graph getBeatGraph(List<OuFuData> ouFuDataList) {
        Graph hrGraph = Graph.builder().type(ReceiveDataType.HEARTBEAT).build();
        for (OuFuData hrData : ouFuDataList) {
            hrGraph.getxArr().add(hrData.getCheckTime());
            hrGraph.getyArr().add(hrData.getHeartbeat());
        }
        return hrGraph;
    }

    private Map getSleepGraph(NewSleepDataView newSleepDataView) {
        Map res = new HashMap();
        res.put("title", newSleepDataView.getBeginTime().substring(0, 10));
        List<Map> list = new ArrayList<>();
        Map map1 = new HashMap();
        map1.put("name", "浅睡眠");
        map1.put("value", newSleepDataView.getSleepingTime1());
        Map map2 = new HashMap();
        map2.put("name", "深睡眠");
        map2.put("value", newSleepDataView.getSleepingTime2());
        Map map3 = new HashMap();
        map3.put("name", "清醒");
        map3.put("value", newSleepDataView.getSleepingTime3());
        Map map4 = new HashMap();
        map4.put("name", "快速眼动");
        map4.put("value", StringUtils.isNotBlank(newSleepDataView.getSleepingTime4()) ?
                newSleepDataView.getSleepingTime4() : 0);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);

        res.put("type", ReceiveDataType.SLEEP);
        res.put("data", list);
        res.put("total", newSleepDataView.getSleepingTimeRange());
        return res;
    }

    private Map getSleepGraph(List<SleepData> sleepDataList) {
        Map res = new HashMap();
        /*if (sleepDataList.size() == 0) {
            res.put("data", new ArrayList<>());
            return res;
        }*/
        double total = 0;
        res.put("title", sleepDataList.get(0).getTime());
        List<Map> list = new ArrayList<>();
        List<String> names = new ArrayList<>();
        for (SleepData sleepData : sleepDataList) {
            String sleepType = sleepData.getSleepType();
            String display = dictValueMapper.selectDictByCodeAndValue("sleepType", sleepType).getDictDisplay();
            Map map = new HashMap();
            map.put("name", display);
            map.put("value", sleepData.getSleepingTimeRange());
            total += sleepData.getSleepingTimeRange();
            list.add(map);
            names.add(display);
        }
        if (names.size() < 4) {
            if (!names.contains("浅睡眠")) {
                Map map = new HashMap();
                map.put("name", "浅睡眠");
                map.put("value", 0);
                list.add(map);
            }
            if (!names.contains("深睡眠")) {
                Map map = new HashMap();
                map.put("name", "深睡眠");
                map.put("value", 0);
                list.add(map);
            }
            if (!names.contains("清醒")) {
                Map map = new HashMap();
                map.put("name", "清醒");
                map.put("value", 0);
                list.add(map);
            }
            if (!names.contains("快速眼动")) {
                Map map = new HashMap();
                map.put("name", "快速眼动");
                map.put("value", 0);
                list.add(map);
            }
        }
        res.put("data", list);
        res.put("total", total);
        return res;
    }


    private Graph getBlutHrGraph(List<Blutdruck> blutdruckList) {
        Graph graph = Graph.builder().build();
        for (Blutdruck blutdruck : blutdruckList) {
            graph.getxArr().add(blutdruck.getCheckTime());
            graph.getyArr().add(blutdruck.getHeartData());
        }
        return graph;
    }

    private Graph getBloodGroup(List<BloodSugar> bloodSugarList) {
        Graph graph = Graph.builder().build();
        for (BloodSugar bloodSugar : bloodSugarList) {
            graph.getxArr().add(bloodSugar.getCheckTime());
            graph.getyArr().add(bloodSugar.getBloodSugar());
        }
        return graph;
    }

    private Graph getBpGraph(List<BpData> bpDataList) {
        Graph bpGraph = Graph.builder().build();
        for (BpData bpData : bpDataList) {
            bpGraph.getxArr().add(bpData.getTime());
            bpGraph.getyArr().add(bpData.getOxygen());
        }
        return bpGraph;
    }

    private Graph getHrGraph(List<HrData> hrDataList) {
        Graph hrGraph = Graph.builder().build();
        for (HrData hrData : hrDataList) {
            hrGraph.getxArr().add(hrData.getTime());
            hrGraph.getyArr().add(hrData.getHr());
        }
        return hrGraph;
    }

    private Graph getBlutGraph(List blutdruckList) {
        Map map1 = new HashMap();
        map1.put("name", "高压");
        List data1 = new ArrayList();
        map1.put("data", data1);

        Map map2 = new HashMap();
        map2.put("name", "低压");
        List data2 = new ArrayList();
        map2.put("data", data2);

        Graph blutGraph = Graph.builder().build();
        List yArr = blutGraph.getyArr();
        yArr.add(map1);
        yArr.add(map2);
        for (Object object : blutdruckList) {
            if (object instanceof Blutdruck) {
                Blutdruck blutdruck = (Blutdruck) object;
                data1.add(blutdruck.getHighData());
                data2.add(blutdruck.getLowData());
                blutGraph.getxArr().add(blutdruck.getCheckTime());
            } else if (object instanceof BpData) {
                BpData bpData = (BpData) object;
                data1.add(bpData.getSystolic());
                data2.add(bpData.getHrv());
                blutGraph.getxArr().add(bpData.getTime());
            } else if (object instanceof OuFuData) {
                OuFuData ouFuData = (OuFuData) object;
                data1.add(ouFuData.getShrink());
                data2.add(ouFuData.getDiastolic());
                blutGraph.getxArr().add(ouFuData.getCheckTime());
            }
        }
        return blutGraph;
    }

    public BaseResult index2(IndexReqDTO indexReqDTO) throws ParseException {
        //构造返回结果
        Graph graph = Graph.builder().build();
        //智能手环数据  欧浮设备
        //if (EquipCategory.ZNSH.equals(indexReqDTO.getEquipCategory())) {
        if (!ReceiveDataType.SLEEP.equals(indexReqDTO.getType())) {
            switch (indexReqDTO.getDateCategory()) {
                case DateCategory.DAY:
                    generateGraphDay(graph, indexReqDTO);
                    break;
                case DateCategory.WEEK:
                    if (ReceiveDataType.DOUBLE_TEMPERATURE.equals(indexReqDTO.getType())) {
                        generateGraphTempWeek(graph, indexReqDTO);
                    } else {
                        //生成周图表
                        generateGraphWeek(graph, indexReqDTO);
                    }
                    break;
                case DateCategory.MONTH:
                    if (ReceiveDataType.DOUBLE_TEMPERATURE.equals(indexReqDTO.getType())) {
                        generateGraphTempMonth(graph, indexReqDTO);
                    } else {
                        //生成月图表
                        generateGraphMonth(graph, indexReqDTO);
                    }
                    break;
                case DateCategory.YEAR:
                    if (ReceiveDataType.STEP.equals(indexReqDTO.getType())) {
                        generateGraphStepYear(graph, indexReqDTO);
                    } else if (ReceiveDataType.DOUBLE_TEMPERATURE.equals(indexReqDTO.getType())) {
                        generateGraphTempYear(graph, indexReqDTO);
                    } else {
                        generateGraphYear(graph, indexReqDTO);
                    }
                    break;
                default:
                    return BaseResult.build(StatusCode.PARAMETER_WRONG);
            }
        } else {
            if (ReceiveDataType.SLEEP.equals(indexReqDTO.getType())) {
                if (EquipCategory.ZNSH.equals(indexReqDTO.getEquipCategory())) {
                    List<NewSleepDataView> newSleepDataViews = ouFuService.getNewSleepDataViews(indexReqDTO.getCustomerId());
                    if (DateCategory.DAY.equals(indexReqDTO.getDateCategory())) {
                        List<NewSleepDataView> dataView = newSleepDataViews.stream().filter(newSleepDataView -> {
                            String beginTime = newSleepDataView.getEndTime();
                            String[] split = beginTime.split("/");
                            String month = Integer.parseInt(split[1]) > 10 ? split[1] : "0" + split[1];
                            String substring = split[2].substring(0, split[2].indexOf(" "));
                            String day = Integer.parseInt(substring) > 10 ? substring : "0" + substring;
                            return indexReqDTO.getStartTime().equals(split[0] + "-" + month + "-" + day);
                        }).collect(Collectors.toList());
                        return BaseResult.ok(dataView.size()>0?dataView.get(0):new NewSleepDataView());
                    } else {
                        List<NewSleepDataView> collect = filter(indexReqDTO, newSleepDataViews);
                        if (DateCategory.WEEK.equals(indexReqDTO.getDateCategory()) || DateCategory.MONTH.equals(indexReqDTO.getDateCategory())) {
                            generateGraphSleep(graph, collect, indexReqDTO);
                        } else if (DateCategory.YEAR.equals(indexReqDTO.getDateCategory())) {
                            generateGraphSleepYear(graph, collect, indexReqDTO);
                        }
                    }
                } else if (EquipCategory.ZNSB.equals(indexReqDTO.getEquipCategory())) {
                    if (DateCategory.DAY.equals(indexReqDTO.getDateCategory())) {
                        NewSleepDataView dataView = sleepDataMapper.selectByTimeAndCustomerId(indexReqDTO.getCustomerId(), indexReqDTO.getStartTime());
                        return BaseResult.ok(dataView);
                    } else if (DateCategory.WEEK.equals(indexReqDTO.getDateCategory()) || DateCategory.MONTH.equals(indexReqDTO.getDateCategory())) {
                        generateGraphSleepWeekOrMonth(graph, indexReqDTO);
                    } else if (DateCategory.YEAR.equals(indexReqDTO.getDateCategory())) {
                        generateGraphSleepYear(graph, indexReqDTO);
                    }
                } else if (EquipCategory.LB.equals(indexReqDTO.getEquipCategory())) {
                    //来邦睡眠
                    if (DateCategory.DAY.equals(indexReqDTO.getDateCategory())) {
                        NewSleepDataView dataView = lbWatchService.getDaySleepByTimeAndCustomerId(indexReqDTO.getCustomerId(), indexReqDTO.getStartTime());
                        return BaseResult.ok(dataView);
                    } else if (DateCategory.WEEK.equals(indexReqDTO.getDateCategory()) || DateCategory.MONTH.equals(indexReqDTO.getDateCategory())) {
                        generateGraphLbSleepWeekOrMonth(graph, indexReqDTO);
                    } else if (DateCategory.YEAR.equals(indexReqDTO.getDateCategory())) {
                        generateGraphLbSleepYear(graph, indexReqDTO);
                    }
                }
            }

        }
        return BaseResult.ok(graph);
    }

    private void generateGraphLbSleepYear(Graph graph, IndexReqDTO indexReqDTO) {
        List<NewSleepDataView>  list =  lbWatchService.selectGraphLbSleepYear(indexReqDTO);
        List<Integer> datelist = list.stream().map(newSleepDataView -> Integer.valueOf(newSleepDataView.getTime().split("-")[1])).collect(Collectors.toList());
        graph.setxArr(datelist);
        List<List> dataList = new ArrayList<>();
        for (NewSleepDataView newSleepDataView : list) {
            List<String> monList = new ArrayList<>();
            monList.add(newSleepDataView.getSleepingTime1());
            monList.add(newSleepDataView.getSleepingTime2());
            monList.add(newSleepDataView.getSleepingTime3());
            dataList.add(monList);
        }
        graph.setyArr(dataList);
    }

    private void generateGraphLbSleepWeekOrMonth(Graph graph, IndexReqDTO indexReqDTO) {
        List<NewSleepDataView>  list =  lbWatchService.selectGraphLbSleepWeekOrMonth(indexReqDTO);
        List<String> dateList = list.stream().map(newSleepDataView -> {
            String format = null;
            try {
                format = DateUtils.format(DateUtil.parseToDate(newSleepDataView.getTime(), DateUtil.FMT_YYYYMMDD), DateUtils.MM_DD);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return format;
        }).collect(Collectors.toList());
        graph.setxArr(dateList);
        graph.setyArr(list);

    }

    private void generateGraphTempYear(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<IndexGraphDayResDTO> list = ouFuService.selectTempDateEveryDay(indexReqDTO);
        Map<String, List<IndexGraphDayResDTO>> collect = list.stream().collect(Collectors.groupingBy(IndexGraphDayResDTO::getDate));
        List<String> fieldResList = new ArrayList<>();
        List<String> field1ResList = new ArrayList<>();
        boolean flag = false;
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            flag = true;
        }
        for (int i = 1; i < 13; i++) {
            graph.getxArr().add(i);
            String date = DateUtils.getYear(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT)) + "-" + (i < 10 ? "0" + i : i + "");
            //String date = DateUtils.format(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT).getTime() + (long) i * 24 * 60 * 60 * 1000, DateUtils.DATE_FORMAT);
            //graph.getxArr().add(DateUtils.format(DateUtils.parse(date, DateUtils.DATE_FORMAT), DateUtils.MM_DD).substring(1));
            if (list.stream().anyMatch(res -> res.getDate().equals(date))) {
                List<IndexGraphDayResDTO> resDTOList = collect.get(date);
                fieldResList.add(resDTOList.get(0).getValue());
                if (flag) {
                    field1ResList.add(resDTOList.get(1).getValue());
                }
            } else {
                fieldResList.add("0");
                if (flag) {
                    field1ResList.add("0");
                }
            }
        }
        graph.getyArr().add(fieldResList);
        if (flag) {
            graph.getyArr().add(field1ResList);
        }
    }

    private void generateGraphTempMonth(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<IndexGraphDayResDTO> list = ouFuService.selectTempDateEveryDay(indexReqDTO);
        Map<String, List<IndexGraphDayResDTO>> collect = list.stream().collect(Collectors.groupingBy(IndexGraphDayResDTO::getDate));
        List<String> fieldResList = new ArrayList<>();
        List<String> field1ResList = new ArrayList<>();
        boolean flag = false;
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            flag = true;
        }
        Date date = DateUtils.formatDate(indexReqDTO.getStartTime());
        while (!DateUtils.formatDate(indexReqDTO.getEndTime()).before(date)) {
            String tip = DateUtils.format(date, DateUtils.DATE_FORMAT);
            String format = DateUtils.format(date, DateUtils.MM_DD);
            graph.getxArr().add(format.startsWith("0") ? format.substring(1) : format);
            //newSleepDataView.setTime(tip);
            if (list.stream().anyMatch(res -> res.getDate().equals(tip))) {
                List<IndexGraphDayResDTO> resDTOList = collect.get(tip);
                fieldResList.add(resDTOList.get(0).getValue());
                if (flag) {
                    field1ResList.add(resDTOList.get(1).getValue());
                }
            } else {
                fieldResList.add("0");
                if (flag) {
                    field1ResList.add("0");
                }
            }
            date = new Date(date.getTime() + (long) 1 * 24 * 60 * 60 * 1000);
        }
        graph.getyArr().add(fieldResList);
        if (flag) {
            graph.getyArr().add(field1ResList);
        }
    }

    private void generateGraphTempWeek(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<IndexGraphDayResDTO> list = ouFuService.selectTempDateEveryDay(indexReqDTO);
        Map<String, List<IndexGraphDayResDTO>> collect = list.stream().collect(Collectors.groupingBy(IndexGraphDayResDTO::getDate));
        List<String> fieldResList = new ArrayList<>();
        List<String> field1ResList = new ArrayList<>();
        boolean flag = false;
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            flag = true;
        }
        graph.getxArr().addAll(Lists.newArrayList("周一", "周二", "周三", "周四", "周五", "周六", "周日"));
        for (int i = 0; i < 7; i++) {
            String date = DateUtils.format(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT).getTime() + (long) i * 24 * 60 * 60 * 1000, DateUtils.DATE_FORMAT);
            //graph.getxArr().add(DateUtils.format(DateUtils.parse(date, DateUtils.DATE_FORMAT), DateUtils.MM_DD).substring(1));
            if (list.stream().anyMatch(res -> res.getDate().equals(date))) {
                List<IndexGraphDayResDTO> resDTOList = collect.get(date);
                fieldResList.add(resDTOList.get(0).getValue());
                if (flag) {
                    field1ResList.add(resDTOList.get(1).getValue());
                }
            } else {
                //IndexGraphResDTO build = IndexGraphResDTO.builder().max("0").min("0").date(date).build();
                fieldResList.add("0");
                if (flag) {
                    field1ResList.add("0");
                }
            }
        }
        graph.getyArr().add(fieldResList);
        if (flag) {
            graph.getyArr().add(field1ResList);
        }
    }

    private void generateGraphStepYear(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        if (EquipCategory.ZNSH.equals(indexReqDTO.getEquipCategory())) {
            List<IndexGraphResDTO> list = ouFuService.selectStepDateEveryDay(indexReqDTO);
            Map<String, List<IndexGraphResDTO>> collect = list.stream().collect(Collectors.groupingBy(indexGraphResDTO -> {
                return indexGraphResDTO.getDate().substring(0, 7);
            }));
            for (int i = 1; i < 13; i++) {
                graph.getxArr().add(i);
                String date = DateUtils.getYear(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT)) + "-" + (i < 10 ? "0" + i : i + "");
                List<IndexGraphResDTO> indexGraphResDTOList = collect.get(date);
                if (indexGraphResDTOList != null && indexGraphResDTOList.size() > 0) {
                    int sum = indexGraphResDTOList.stream().mapToInt(res -> Integer.parseInt(res.getMax())).sum();
                    graph.getyArr().add(sum);
                } else {
                    graph.getyArr().add(0);
                }
            }
        } else if (EquipCategory.ZNSB.equals(indexReqDTO.getEquipCategory())) {
            List<IndexGraphResDTO> list = stepDataMapper.selectStepGraphData(indexReqDTO);
            for (int i = 1; i < 13; i++) {
                graph.getxArr().add(i);
                String date = DateUtils.getYear(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT)) + "-" + (i < 10 ? "0" + i : i + "");
                if (list.stream().anyMatch(res -> res.getDate().equals(date))) {
                    graph.getyArr().add(list.stream().filter(res -> res.getDate().equals(date)).findFirst().get().getMax());
                } else {
                    graph.getyArr().add(0);
                }
            }
        }else if (EquipCategory.LB.equals(indexReqDTO.getEquipCategory())) {
            List<IndexGraphResDTO> list = lbWatchService.selectStepGraphData(indexReqDTO);
            for (int i = 1; i < 13; i++) {
                graph.getxArr().add(i);
                String date = DateUtils.getYear(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT)) + "-" + (i < 10 ? "0" + i : i + "");
                if (list.stream().anyMatch(res -> res.getDate().equals(date))) {
                    graph.getyArr().add(list.stream().filter(res -> res.getDate().equals(date)).findFirst().get().getMax());
                } else {
                    graph.getyArr().add(0);
                }
            }
        }
    }

    private void generateGraphSleepYear(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<NewSleepDataView> list = sleepDataMapper.selectByPara(indexReqDTO);
        Map<String, List<NewSleepDataView>> collect = list.stream().collect(Collectors.groupingBy(sleep -> sleep.getTime().substring(0, 7)));
        for (int i = 1; i < 13; i++) {
            graph.getxArr().add(i);
            String date = DateUtils.getYear(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT)) + "-" + (i < 10 ? "0" + i : i + "");
            List<NewSleepDataView> newSleepDataViews = collect.get(date);
            if (newSleepDataViews != null) {
                double time1 = newSleepDataViews.stream().mapToDouble(sleep -> Double.parseDouble(sleep.getSleepingTime1())).sum();
                double time2 = newSleepDataViews.stream().mapToDouble(sleep -> Double.parseDouble(sleep.getSleepingTime2())).sum();
                double time3 = newSleepDataViews.stream().mapToDouble(sleep -> Double.parseDouble(sleep.getSleepingTime3())).sum();
                double time4 = newSleepDataViews.stream().mapToDouble(sleep -> Double.parseDouble(sleep.getSleepingTime4())).sum();
                double total = time1 + time2 + time3 + time4;
                //String rang1 = String.format("%.2f", time1 / total);
                //String rang2 = String.format("%.2f", time2 / total);
                //String rang3 = String.format("%.2f", time3 / total);
                //BigDecimal decimal = new BigDecimal("1").subtract(new BigDecimal(rang1).add(new BigDecimal(rang2)).add(new BigDecimal(rang3)));
                ArrayList<String> arrayList = Lists.newArrayList(String.valueOf(time1), String.valueOf(time2), String.valueOf(time3), String.valueOf(time4));
                graph.getyArr().add(arrayList);
            } else {
                ArrayList<String> arrayList = Lists.newArrayList("0", "0", "0", "0");
                graph.getyArr().add(arrayList);
            }
        }
    }

    private void generateGraphSleepWeekOrMonth(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<NewSleepDataView> list = sleepDataMapper.selectByPara(indexReqDTO);
        List<String> strings = list.stream().map(NewSleepDataView::getTime).collect(Collectors.toList());
        Date date = DateUtils.formatDate(indexReqDTO.getStartTime());
        while (!DateUtils.formatDate(indexReqDTO.getEndTime()).before(date)) {
            String tip = DateUtils.format(date, DateUtils.DATE_FORMAT);
            String format = DateUtils.format(date, DateUtils.MM_DD);
            graph.getxArr().add(format.startsWith("0") ? format.substring(1) : format);
            NewSleepDataView newSleepDataView = new NewSleepDataView();
            //newSleepDataView.setTime(tip);
            if (strings.contains(tip)) {
                graph.getyArr().add(list.stream().filter(sleepDataView -> sleepDataView.getTime().equals(tip)).findFirst().get());
            } else {
                graph.getyArr().add(newSleepDataView);
            }
            date = new Date(date.getTime() + (long) 1 * 24 * 60 * 60 * 1000);
        }

    }

    private void generateGraphSleepYear(Graph graph, List<NewSleepDataView> collect, IndexReqDTO indexReqDTO) throws ParseException {
        Map<String, List<NewSleepDataView>> map = collect.stream().collect(Collectors.groupingBy(sleepDataView -> {
            String beginTime = sleepDataView.getBeginTime();
            String[] split = beginTime.split("/");
            String s = Integer.parseInt(split[1]) > 10 ? split[1] : "0" + split[1];
            return split[0] + "-" + s;
        }));
        for (int i = 1; i < 13; i++) {
            graph.getxArr().add(i);
            String date = DateUtils.getYear(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT)) + "-" + (i < 10 ? "0" + i : i + "");
            List<NewSleepDataView> newSleepDataViews = map.get(date);
            if (newSleepDataViews != null) {
                int time1 = newSleepDataViews.stream().mapToInt(sleep -> Integer.parseInt(sleep.getSleepingTime1().replace("分钟", ""))).sum();
                int time2 = newSleepDataViews.stream().mapToInt(sleep -> Integer.parseInt(sleep.getSleepingTime2().replace("分钟", ""))).sum();
                int time3 = newSleepDataViews.stream().mapToInt(sleep -> Integer.parseInt(sleep.getSleepingTime3().replace("分钟", ""))).sum();
                int total = time1 + time2 + time3;
//                String rang1 = String.format("%.2f", (float) time1 / total);
//                String rang2 = String.format("%.2f", (float) time2 / total);
//                //String rang3 = String.format("%.2f", time3 / total);
//                BigDecimal decimal = new BigDecimal("1").subtract(new BigDecimal(rang1).add(new BigDecimal(rang2)));
                ArrayList<String> arrayList = Lists.newArrayList(String.valueOf(time1), String.valueOf(time2), String.valueOf(time3));
                graph.getyArr().add(arrayList);
            } else {
                ArrayList<String> arrayList = Lists.newArrayList("0", "0", "0");
                graph.getyArr().add(arrayList);
            }
        }
    }

    private List<NewSleepDataView> filter(IndexReqDTO indexReqDTO, List<NewSleepDataView> newSleepDataViews) {
        List<NewSleepDataView> collect = newSleepDataViews.stream().filter(newSleepDataView -> {
            String beginTime = newSleepDataView.getBeginTime();
            String s = beginTime.substring(0, beginTime.indexOf(" ")).replaceAll("/", "-");
            try {
                Date date = DateUtils.parse(s, DateUtils.DATE_FORMAT);
                Date start = DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT);
                Date end = DateUtils.parse(indexReqDTO.getEndTime(), DateUtils.DATE_FORMAT);
                return !date.before(start) && !date.after(end);
            } catch (ParseException e) {
                return false;
            }
        }).collect(Collectors.toList());
        return collect;
    }

    private void generateGraphSleep(Graph graph, List<NewSleepDataView> collect, IndexReqDTO indexReqDTO) throws ParseException {
        Date date = DateUtils.formatDate(indexReqDTO.getStartTime());
        List<String> strings = collect.stream().map(sleepDataView -> sleepDataView.getBeginTime().substring(0, sleepDataView.getBeginTime().indexOf(" "))).collect(Collectors.toList());
        while (!DateUtils.formatDate(indexReqDTO.getEndTime()).before(date)) {
            String tip = DateUtils.format(date, DateUtils.DATE_FORMAT).replaceAll("-", "/").replace("/0", "/");
            String format = DateUtils.format(date, DateUtils.MM_DD);
            graph.getxArr().add(format.startsWith("0") ? format.substring(1) : format);
            NewSleepDataView newSleepDataView = new NewSleepDataView();
            //newSleepDataView.setTime(tip);
            if (strings.contains(tip)) {
                newSleepDataView = collect.stream().filter(sleepDataView -> sleepDataView.getBeginTime().substring(0, sleepDataView.getBeginTime().indexOf(" ")).equals(tip)).findFirst().get();
                //newSleepDataView.setTime(tip);
                newSleepDataView.setSleepingTime1(newSleepDataView.getSleepingTime1().replaceAll("分钟", ""));
                newSleepDataView.setSleepingTime2(newSleepDataView.getSleepingTime2().replaceAll("分钟", ""));
                newSleepDataView.setSleepingTime3(newSleepDataView.getSleepingTime3().replaceAll("分钟", ""));
                newSleepDataView.setSleepingTimeRange(newSleepDataView.getSleepingTimeRange().replaceAll("分钟", ""));
                graph.getyArr().add(newSleepDataView);
            } else {
                graph.getyArr().add(newSleepDataView);
            }
            date = new Date(date.getTime() + (long) 1 * 24 * 60 * 60 * 1000);
        }
    }

    private void generateGraphYear(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<IndexGraphResDTO> indexGraphResDTOList = generateIndexGraphResDTOList(indexReqDTO);
        Map<String, List<IndexGraphResDTO>> collect = indexGraphResDTOList.stream().collect(Collectors.groupingBy(IndexGraphResDTO::getDate));
        List<IndexGraphResDTO> fieldResList = new ArrayList<>();
        List<IndexGraphResDTO> field1ResList = new ArrayList<>();
        boolean flag = false;
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            flag = true;
        }
        //graph.getxArr().addAll(Lists.newArrayList("周一", "周二", "周三", "周四", "周五", "周六", "周日"));
        for (int i = 1; i < 13; i++) {
            graph.getxArr().add(i);
            String date = DateUtils.getYear(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT)) + "-" + (i < 10 ? "0" + i : i + "");
            //graph.getxArr().add(DateUtils.format(DateUtils.parse(date, DateUtils.DATE_FORMAT), DateUtils.MM_DD).substring(1));
            if (indexGraphResDTOList.stream().anyMatch(indexGraphResDTO -> indexGraphResDTO.getDate().equals(date))) {
                List<IndexGraphResDTO> resDTOList = collect.get(date);
                fieldResList.add(resDTOList.get(0));
                if (flag) {
                    field1ResList.add(resDTOList.get(1));
                }
            } else {
                IndexGraphResDTO build = IndexGraphResDTO.builder().max("0").min("0").date(date).build();
                fieldResList.add(build);
                if (flag) {
                    field1ResList.add(build);
                }
            }
        }
        graph.getyArr().add(fieldResList);
        if (flag) {
            graph.getyArr().add(field1ResList);
        }
    }

    private void generateGraphDay(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<IndexGraphDayResDTO> resDTOList = generateIndexGraphDayResDTOList(indexReqDTO);
        /*List<String> timeList = resDTOList.stream().map(indexGraphDayResDTO -> indexGraphDayResDTO.getDate()).collect(Collectors.toList());
        List<String> valueList = resDTOList.stream().map(indexGraphDayResDTO -> indexGraphDayResDTO.getValue()).collect(Collectors.toList());
        graph.getyArr().add(valueList);
        graph.getxArr().add(timeList);*/
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            Map<String, List<IndexGraphDayResDTO>> map = resDTOList.stream().collect(Collectors.groupingBy(IndexGraphDayResDTO::getDate));
            List<String> xlist = new ArrayList<>();
            List<String> y1list = new ArrayList<>();
            List<String> y2list = new ArrayList<>();
            for (String key : map.keySet()) {
                List<IndexGraphDayResDTO> dtos = map.get(key);
                List<String> valueList = dtos.stream().sorted(Comparator.comparing(IndexGraphDayResDTO::getValue).reversed()).map(indexGraphDayResDTO -> indexGraphDayResDTO.getValue()).collect(Collectors.toList());
                xlist.add(key);
                if (indexReqDTO.getEquipCategory().equals(EquipCategory.LB)) {
                    y1list.add(valueList.get(1));
                    y2list.add(valueList.get(0));
                } else {
                    y1list.add(valueList.get(0));
                    y2list.add(valueList.get(1));
                }
            }
            if (xlist!=null && xlist.size() > 0) {
                graph.setxArr(xlist);
                graph.getyArr().add(y1list);
                graph.getyArr().add(y2list);
            }
        } else {
            List<String> timeList = resDTOList.stream().map(indexGraphDayResDTO -> indexGraphDayResDTO.getDate()).collect(Collectors.toList());
            List<String> valueList = resDTOList.stream().map(indexGraphDayResDTO -> indexGraphDayResDTO.getValue()).collect(Collectors.toList());
            graph.setyArr(valueList);
            graph.setxArr(timeList);
        }

        /*Map<String, List<IndexGraphDayResDTO>> collect = resDTOList.stream().collect(Collectors.groupingBy(IndexGraphDayResDTO::getDate));
        List<String> fieldResList = new ArrayList<>();
        List<String> field1ResList = new ArrayList<>();
        boolean flag = false;
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            flag = true;
        }
        for (int i = 0; i <= 23; i++) {
            String key = i < 10 ? "0" + i : i + "";
            graph.getxArr().add(key);
            if (resDTOList.stream().anyMatch(IndexGraphDayResDTO -> IndexGraphDayResDTO.getDate().equals(key))) {
                List<IndexGraphDayResDTO> list = collect.get(key);
                fieldResList.add(list.get(0).getValue());
                if (flag) {
                    field1ResList.add(list.get(1).getValue());
                }
            } else {
                //IndexGraphResDTO build = IndexGraphResDTO.builder().max("0").min("0").date(key).build();
                //IndexGraphDayResDTO build = IndexGraphDayResDTO.builder().date(key).value("0").build();
                fieldResList.add("0");
                if (flag) {
                    field1ResList.add("0");
                }
            }
        }
        graph.getyArr().add(fieldResList);
        if (flag) {
            graph.getyArr().add(field1ResList);
        }*/
    }


    private void generateGraphMonth(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<IndexGraphResDTO> indexGraphResDTOList = generateIndexGraphResDTOList(indexReqDTO);
        Map<String, List<IndexGraphResDTO>> collect = indexGraphResDTOList.stream().collect(Collectors.groupingBy(IndexGraphResDTO::getDate));
        Date date = DateUtils.formatDate(indexReqDTO.getStartTime());
        List<IndexGraphResDTO> fieldResList = new ArrayList<>();
        List<IndexGraphResDTO> field1ResList = new ArrayList<>();
        boolean flag = false;
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            flag = true;
        }

        while (!DateUtils.formatDate(indexReqDTO.getEndTime()).before(date)) {
            String tip = DateUtils.formatDate(date);
            String format = DateUtils.format(date, DateUtils.MM_DD);
            graph.getxArr().add(format.startsWith("0") ? format.substring(1) : format);
            if (indexGraphResDTOList.stream().anyMatch(indexGraphResDTO -> indexGraphResDTO.getDate().equals(tip))) {
                List<IndexGraphResDTO> resDTOList = collect.get(tip);
                fieldResList.add(resDTOList.get(0));
                if (flag) {
                    field1ResList.add(resDTOList.get(1));
                }
            } else {
                IndexGraphResDTO build = IndexGraphResDTO.builder().max("0").min("0").date(tip).build();
                fieldResList.add(build);
                if (flag) {
                    field1ResList.add(build);
                }
            }
            date = new Date(date.getTime() + (long) 1 * 24 * 60 * 60 * 1000);
        }
        graph.getyArr().add(fieldResList);
        if (flag) {
            graph.getyArr().add(field1ResList);
        }
    }

    private void generateGraphWeek(Graph graph, IndexReqDTO indexReqDTO) throws ParseException {
        List<IndexGraphResDTO> indexGraphResDTOList = generateIndexGraphResDTOList(indexReqDTO);
        Map<String, List<IndexGraphResDTO>> collect = indexGraphResDTOList.stream().collect(Collectors.groupingBy(IndexGraphResDTO::getDate));
        List<IndexGraphResDTO> fieldResList = new ArrayList<>();
        List<IndexGraphResDTO> field1ResList = new ArrayList<>();
        boolean flag = false;
        if (indexReqDTO.getType().equals(ReceiveDataType.DOUBLE_TEMPERATURE) || indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            flag = true;
        }
        graph.getxArr().addAll(Lists.newArrayList("周一", "周二", "周三", "周四", "周五", "周六", "周日"));
        for (int i = 0; i < 7; i++) {
            String date = DateUtils.format(DateUtils.parse(indexReqDTO.getStartTime(), DateUtils.DATE_FORMAT).getTime() + (long) i * 24 * 60 * 60 * 1000, DateUtils.DATE_FORMAT);
            //graph.getxArr().add(DateUtils.format(DateUtils.parse(date, DateUtils.DATE_FORMAT), DateUtils.MM_DD).substring(1));
            if (indexGraphResDTOList.stream().anyMatch(indexGraphResDTO -> indexGraphResDTO.getDate().equals(date))) {
                List<IndexGraphResDTO> resDTOList = collect.get(date);
                fieldResList.add(resDTOList.get(0));
                if (flag) {
                    field1ResList.add(resDTOList.get(1));
                }
            } else {
                IndexGraphResDTO build = IndexGraphResDTO.builder().max("0").min("0").date(date).build();
                fieldResList.add(build);
                if (flag) {
                    field1ResList.add(build);
                }
            }
        }
        graph.getyArr().add(fieldResList);
        if (flag) {
            graph.getyArr().add(field1ResList);
        }

    }

    private List<IndexGraphResDTO> generateIndexGraphResDTOList(IndexReqDTO indexReqDTO) {
        List<IndexGraphResDTO> indexGraphResDTOList = new ArrayList<>();
        if (EquipCategory.ZNSH.equals(indexReqDTO.getEquipCategory())) {
            indexGraphResDTOList = ouFuService.selectGraphWithDate(indexReqDTO);
        } else if (EquipCategory.XDY.equals(indexReqDTO.getEquipCategory())) {
            indexGraphResDTOList = heartVoiceService.selectGraphData(indexReqDTO);
        } else if (EquipCategory.XYY.equals(indexReqDTO.getEquipCategory())) {
            indexGraphResDTOList = blutdruckMapper.selectGraphData(indexReqDTO);
        } else if (EquipCategory.ZNSB.equals(indexReqDTO.getEquipCategory())) {
            if (!ReceiveDataType.STEP.equals(indexReqDTO.getType())) {
                indexGraphResDTOList = stepDataMapper.selectGraphData(indexReqDTO);
            } else {
                indexGraphResDTOList = stepDataMapper.selectStepGraphData(indexReqDTO);
            }
        } else if (EquipCategory.POCT4.equals(indexReqDTO.getEquipCategory())) {
            indexGraphResDTOList = poct4Mapper.selectGraphData(indexReqDTO);
        } else if (EquipCategory.POCT7.equals(indexReqDTO.getEquipCategory())) {
            indexGraphResDTOList = poct8Mapper.selectGraphData(indexReqDTO);
        } else if (EquipCategory.XTY.equals(indexReqDTO.getEquipCategory())) {
            indexGraphResDTOList = bloodSugarMapper.selectGraphData(indexReqDTO);
        } else if (EquipCategory.LB.equals(indexReqDTO.getEquipCategory())) {
            indexGraphResDTOList = lbWatchService.selectGraphData(indexReqDTO);
        }
        return indexGraphResDTOList;
    }

    private List<IndexGraphDayResDTO> generateIndexGraphDayResDTOList(IndexReqDTO indexReqDTO) {
        List<IndexGraphDayResDTO> resDTOList = new ArrayList<>();
        if (EquipCategory.ZNSH.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = ouFuService.selectGraphWithDay(indexReqDTO);
        } else if (EquipCategory.XDY.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = heartVoiceService.selectGraphWithDay(indexReqDTO);
        } else if (EquipCategory.XYY.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = blutdruckMapper.selectGraphWithDay(indexReqDTO);
        } else if (EquipCategory.ZNSB.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = stepDataMapper.selectGraphWithDay(indexReqDTO);
        } else if (EquipCategory.POCT4.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = poct4Mapper.selectGraphWithDay(indexReqDTO);
        } else if (EquipCategory.POCT7.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = poct8Mapper.selectGraphWithDay(indexReqDTO);
        } else if (EquipCategory.XTY.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = bloodSugarMapper.selectGraphWithDay(indexReqDTO);
        } else if (EquipCategory.LB.equals(indexReqDTO.getEquipCategory())) {
            resDTOList = lbWatchService.selectGraphWithDay(indexReqDTO);
        }
        return resDTOList;
    }
}
